package com.example.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class TestService extends Service{

	static public int SEVER_PORT = 7890;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public void onCreate() {
		super.onCreate();
		//Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();

		Thread initBkgThread = new Thread(new Runnable(){
			public void run() {
				buildServer();
			}
		});
		initBkgThread.start();

	}
	
	public void onDestroy(){
		super.onDestroy();
	}

	private void buildServer(){

		try {

			Boolean end = false;
		    ServerSocket server = new ServerSocket(SEVER_PORT);
		    while(!end){
		    	//Server is waiting for client here, if needed
		        Socket socket = server.accept();
		        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
	            String message = (String) ois.readObject();
		        Log.d("Tcp Example", "From client: "+message);

		        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
	            oos.writeObject("Good bye and thanks for all the fish :)");
		        //output.println("Good bye and thanks for all the fish :)");
		        socket.close();
		        //if ( STOPPING conditions){ end = true; }
		    }
		    server.close();
		             
		} catch (UnknownHostException e) {
		 
			 // TODO Auto-generated catch block
		     e.printStackTrace();
		    
		 } catch (IOException e) {
		      
			 // TODO Auto-generated catch block
		     
			 e.printStackTrace();
		     
		 } catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
